import 'dart:convert';
import 'package:common_utils/common_utils.dart';
import 'package:get/get.dart';

class ApiProvider extends GetConnect {
	@override
	void onInit() {
		super.onInit();
		httpClient.baseUrl = "http://localhost:8000";

		// 请求拦截
		httpClient.addRequestModifier<void>((request) {
			request.headers['Authorization'] = '12345678';
			return request;
		});

		// 响应拦截
		httpClient.addResponseModifier((request, response) {
			LogUtil.v(response.statusCode,tag: "response.statusCode");
			if(response.statusCode!>299){
				final body=jsonDecode(response.bodyString!);
       			// ignore: prefer_interpolation_to_compose_strings
				var errorMsg="${response.statusCode} "+(body["message"]??response.statusText);
				var error={
					"url":request.url,
					"method":request.method,
					"message":errorMsg
				};
				LogUtil.v(error,tag: "请求网络失败");
       			return Future.error(error);
			}else{
				final body=jsonDecode(response.bodyString!);
				if(body["code"]==0){
					return response;
				}else{
					var error={
						"url":request.url,
						"method":request.method,
						"message":body["message"]
					};
					LogUtil.v(error,tag: "请求业务失败");
					return Future.error(error);
				}
			}
		});
	}
}

